<template>
  <div class="page-coursedetail">
    <div class="page-position">
      <div class="breadcrumb-box">
        <a class="breadcrumb-item" @click="$router.push('/classify')">{{
          $t("locale.pc.mycourse.coursedetail.t1")
        }}</a>
        <span class="breadcrumb-arrow">
          <van-icon name="arrow" size="16" />
        </span>
        <a
          class="breadcrumb-item"
          @click="$router.push('/classify?id=' + course_obj.majorId)"
          >{{ course_obj.majorName }}</a
        >
        <span class="breadcrumb-arrow">
          <van-icon name="arrow" size="16" />
        </span>
        <a class="breadcrumb-item breadcrumb-item-active">{{
          course_obj.courseName
        }}</a>
        <span class="breadcrumb-arrow">
          <van-icon name="arrow" size="16" />
        </span>
      </div>
      <!-- 头部介绍 -->
      <div class="top-introduce">
        <div class="img-position">
          <img :src="course_obj.iconPath" />
          <div class="box-play" v-show="false"></div>
          <div class="play" v-show="false">
            <Icon
              type="md-play"
              color="#edf0f5"
              :size="50"
              style="margin-top: 14px;margin-left: 18px;"
            />
          </div>
        </div>
        <div class="center-content" v-if="!is_had_course">
          <div class="title">
            {{ course_obj.courseName }}
          </div>
          <div class="chapter-people" style="">
            <div class="chapter-number">
              <span>本课程共有</span>
              <span class="number">{{ course_obj.videoNum }}</span>
              <span>小节</span>
            </div>
            <div class="buy-people">
              <span>已报名</span>
              <span class="people">{{ course_obj.studentSum }}</span>
              <span>人</span>
            </div>
          </div>
          <div class="course-date">
            课程限期：{{ formatDate(course_obj.buyCourseStartDate, 2) }} 至
            {{ formatDate(course_obj.buyCourseDeadlineDate, 2) }}
          </div>
          <div class="course-info">
            <div>课程简介：</div>
            <div class="info">
              {{ course_obj.goal }}
            </div>
          </div>
          <div class="online"></div>
          <div class="buy-price">
            <div
              class="member-price"
              v-if="
                course_obj.isFree == 0 && !course_obj.isDiscount && is_member
              "
            >
              <span class="m-f" v-if="isMemberFree">会员免费</span>
              <span class="m-t" v-else
                >会员价：￥<span class="m-p">{{
                  Number(
                    user_member.memberLevel === 0
                      ? course_obj.smallMemberPrice
                      : user_member.memberLevel === 1
                      ? course_obj.middleMemberPrice
                      : user_member.memberLevel === 2
                      ? course_obj.highMemberPrice
                      : 0
                  ).toFixed(2)
                }}</span></span
              >
            </div>
            <div class="original-price">
              <div>
                <span style="font-size: 16px;font-weight: bold;color: #494a4d;"
                  >价格：</span
                >
                <span style="font-size: 16px;font-weight: bold;color: #ff8a8a;"
                  >￥</span
                >
                <span
                  style="font-size: 26px;font-weight: bold;color: #ff8a8a;"
                  v-if="course_obj.isFree == 0"
                  >{{
                    course_obj.isDiscount
                      ? course_obj.discountPrice
                      : course_obj.price
                  }}</span
                >
                <span
                  style="font-size: 26px;font-weight: bold;color: #ff8a8a;"
                  v-if="course_obj.isFree == 1"
                  >免费</span
                >
              </div>

              <Button
                type="primary"
                style="margin-left:10px;"
                :disabled="buyStatus"
                @click="
                  $router.push({ path: '/coursebuy', query: { id: courseId } })
                "
                >{{buyStatus ? '尚未开放' : '购买课程'}}</Button
              >
            </div>
          </div>
        </div>
        <div class="center-content" v-if="is_had_course">
          <div class="title">
            {{ course_obj.courseName }}
          </div>
          <div class="chapter-people">
            <div class="chapter-number">
              <span>本课程共有</span>
              <span class="number">{{ course_obj.videoNum }}</span>
              <span>小节</span>
              <span style="margin-left:20px;">已报名</span>
              <span class="people">{{ course_obj.studentSum }}</span>
              <span>人</span>
            </div>
            <!-- $router.push({ path: '/play', query: { id: courseId } }) -->
            <div class="buy-people">
              <Button type="primary" style="margin-left:10px;" @click="toLearn"
                >立即学习</Button
              >
            </div>
          </div>
          <div class="course-date">
            课程限期：{{ formatDate(course_obj.buyCourseStartDate, 2) }} 至
            {{ formatDate(course_obj.buyCourseDeadlineDate, 2) }}
          </div>

          <div class="online" style="margin-bottom:20px;"></div>
          <div class="course-info">
            <div>课程简介：</div>
            <div class="info">
              {{ course_obj.goal }}
            </div>
          </div>
        </div>
      </div>
      <!-- 主体详情 -->
      <div class="body-position">
        <!-- 详情 -->
        <div class="left-detail" ref="left-position">
          <Tabs :value="active_tap">
            <TabPane
              :label="$t('locale.pc.mycourse.coursedetail.t14')"
              name="detail"
            >
              <div class="introduce">
                <div class="id-it ql-snow">
                  <div
                    class="rich-text ql-container ql-editor ql-snow"
                    v-html="course_obj.introduce"
                  ></div>
                </div>
              </div>
            </TabPane>
            <TabPane
              :label="$t('locale.pc.mycourse.coursedetail.t19')"
              name="chapter"
            >
              <chapter-tree
                :datas="chapter_tree"
                :isBuy="is_had_course"
                :tabType="'chapter'"
              ></chapter-tree>
            </TabPane>
            <!-- <TabPane
              label="课程作业"
              name="task"
              v-show="is_had_course && kl_md.KLZYGL == 1"
            >
              <chapter-tree
                :datas="chapter_tree"
                :isBuy="is_had_course"
                :tabType="'task'"
                :getChapterList="getChapterList"
              ></chapter-tree>
            </TabPane> -->
            
            <TabPane
              :label="$t('locale.pc.mycourse.coursedetail.t20')"
              name="courseware"
              v-if="false"
            >
              <a
                class="download-btn"
                @click="handleDownload(chapter_obj.courseWarePath)"
                >{{ $t("locale.pc.mycourse.coursedetail.t20") }}</a
              >
              <iframe
                :src="
                  `https://view.officeapps.live.com/op/embed.aspx?src=${encodeURIComponent(
                    chapter_obj.courseWarePath
                  )}`
                "
                v-if="isMircosoftRead"
                class="preview-iframe"
                frameborder="0"
              >
                This is an embedded
                <a target="_blank" href="http://office.com">Microsoft Office</a>
                document, powered by
                <a target="_blank" href="http://office.com/webapps"
                  >Office Online</a
                >
              </iframe>
              <!-- <img
                class="preview-img"
                :src="chapter_obj.courseWarePath"
                v-if="
                  /.(gif|jpg|jpeg|png|gif|jpg|png)$/.test(
                    chapter_obj.courseWarePath
                  )
                "
              /> -->
            </TabPane>
            <TabPane
              :label="'课程评价(' + commentCount.allRate + ')'"
              name="comment"
              v-if="kl_md.KLKCPJ == 1"
            >
            <div class="section_comment">
              <div class="comment_filter">
                <div class="comment_statistics">
                  <span class="statistics_num">{{ commentCount.goodPercentage }}%</span>
                  <span>好评度</span>
                </div>
                <div class="filter_comment_rank">
                  <RadioGroup v-model="comment_rank" @on-change="(v)=>commentHandle(v)">
                      <Radio label="0">
                          <span>全部评价({{ commentCount.allRate }})</span>
                      </Radio>
                      <Radio label="1">
                          <span>好评({{ commentCount.goodRate }})</span>
                      </Radio>
                      <Radio label="2">
                          <span>中评({{ commentCount.mediumRate }})</span>
                      </Radio>
                      <Radio label="3">
                          <span>差评({{ commentCount.badRate }})</span>
                      </Radio>
                  </RadioGroup>
                </div>
              </div>
              <ul class="comment_list">
                <li class="comment_item" v-for="(item,index) in comment_list" :key="item.id">
                  <div class="item_left">
                    <img class="user_avatar" :src="item.avatar ? item.avatar : '/img/mobile/user_nav_head.png'" alt="">
                    <p class="user_name">{{item.acName}}</p>
                  </div>
                  <div class="item_right">
                    <div class="star_list">
                      <Rate :value="item.rate" disabled/>
                      <Tag type="border" color="primary" v-if="item.isTop">置顶</Tag>
                    </div>
                    <div class="comment_bd">
                      <p v-if="item.content">{{item.content}}</p>
                      <p v-else>{{item.rate | formatRate}}</p>
                    </div>
                    <div class="comment_ft">
                      <span class="comment_time">{{formatDate(item.createTime,1)}}</span>
                    </div>
                    <div class="comment_reply" v-if="item.reply">
                      <div class="reply_bd"> <strong class="reply_tt">老师回复：</strong> {{item.reply}}</div>
                      <div class="comment_ft">
                        <span class="comment_time">{{formatDate(item.replyTime,1)}}</span>
                      </div>
                    </div>
                  </div>
                </li>
              </ul>
              <div class="pagination" style="text-align:center;" v-if="comment.total > 0">
                <Page
                  :total="comment.total"
                  :current="comment.page"
                  :page-size="comment.pageSize"
                  @on-change="commentChangePageHandle"
                ></Page>
              </div>
            </div>
            </TabPane>
            <TabPane
              label="课程作业"
              name="task"
              v-if="is_had_course && kl_md.KLZYGL == 1"
            >
              <div class="course_task_list">
                <div
                  class="task_item"
                  v-for="(item, index) in myTaskList"
                  :key="item.id"
                >
                  <p class="task_name">
                    <span style="color: #707780;"
                      >课程作业{{ index + 1 }}-</span
                    >
                    《<span style="color: #43474c;">{{ item.videoName }}</span
                    >》
                    <span style="color: var(--theme-color);">{{
                      item.taskName
                    }}</span>
                  </p>
                  <div class="task_btn_list">
                    <div
                      class="task_btn_item"
                      v-if="item.resourceUrl"
                      @click="downloadExport(item.resourceUrl, item.taskName)"
                    >
                      下载资源
                    </div>
                    <Upload
                      action="#"
                      :before-upload="handleUploadTask"
                      :show-upload-list="false"
                      v-if="item.taskType == 2"
                    >
                      <div
                        :class="[
                          'task_btn_item',
                          item.userTask ? 'task_btn_gray' : 'task_btn_pink'
                        ]"
                        @click="setTask(item, !!item.userTask, $event)"
                      >
                        {{ item.userTask ? "已经完成" : "上传作业" }}
                      </div>
                    </Upload>
                    <div
                      v-else
                      :class="[
                        'task_btn_item',
                        item.userTask ? 'task_btn_gray' : 'task_btn_pink'
                      ]"
                      @click="setTask(item, !!item.userTask, $event)"
                    >
                      {{ item.userTask ? "已经完成" : "开始考试" }}
                    </div>
                  </div>
                </div>
              </div>
              <div class="empty_task" v-if="myTaskList.length == 0">
                <Icon type="md-school" size="70" />
                <p>暂无课程作业哟</p>
              </div>
            </TabPane>
          </Tabs>
        </div>
        <div class="right-mentor">
          <span>{{ $t("locale.pc.mycourse.coursedetail.t22") }}</span>
          <div class="online"></div>
          <div class="mentor-mess">
            <div class="portrait">
              <img :src="course_obj.avatar" />
            </div>
            <div class="abstract">
              <ul>
                <li class="m1">
                  <p>{{ course_obj.acName }}</p>
                  {{ $t("locale.pc.mycourse.coursedetail.t23") }}
                </li>
                <li class="m3" style="line-height:32px;">
                  <span v-if="course_obj.designation">{{
                    course_obj.designation
                  }}</span>
                  <span v-else>暂无教师称号</span>
                </li>
              </ul>
            </div>
          </div>
          <div class="teacher_introduce">
            <span v-if="course_obj.ftIntroduce">{{
              course_obj.ftIntroduce
            }}</span>
            <span v-else>暂无教师个人简介</span>
          </div>
        </div>
      </div>
    </div>
    <div
      class="course-agreement"
      v-if="isShowCourseAgreement && kl_md.KLKCXY == 1"
    >
      <div class="agreement-box">
        <div class="agreement-header">课程协议</div>
        <div class="agreement-content">
          <div class="introduce ql-snow">
            <div
              class="ql-editor"
              v-html="courseAgreementObj && courseAgreementObj.agreementContent"
            ></div>
          </div>
        </div>
        <div class="agreement-footer">
          <Form
            ref="agreementForm"
            class="footer-form"
            :label-width="80"
            :model="agreementForm"
            :rules="agreementFormRule"
            inline
          >
            <FormItem prop="userName" label="姓名">
              <Input
                type="text"
                v-model="agreementForm.userName"
                placeholder="请输入姓名"
              >
                <Icon type="ios-person-outline" slot="prepend"></Icon>
              </Input>
            </FormItem>
            <FormItem prop="idNumber" label="身份证">
              <Input
                type="text"
                v-model="agreementForm.idNumber"
                style="width:200px;"
                placeholder="请输入身份证号"
              >
                <Icon type="ios-card-outline" slot="prepend" />
              </Input>
            </FormItem>
            <FormItem>
              <Button
                type="primary"
                @click="handleSubmitAgreement('agreementForm')"
                >同意</Button
              >
            </FormItem>
          </Form>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import { getCourseDetailById, downloadReport,getCourseCommentList,getCommentCount } from "~/api/course";
import {
  getCourseAgreement,
  saveCourseAgreement
} from "~/api/course-agreement";
import { getChapter } from "~/api/chapter";
import ChapterTree from "~/components/pc/ChapterTree";
import VideosPlayer from "~/components/mobile/VideosPlayer";
import { mapState, mapActions, mapMutations } from "vuex";
import { getMimeType } from "~/utils/commonfun";
import { blobToDataURL } from "~/utils/file";
import { downloadFile } from "~/api/common";
import { saveOrder } from "~/api/order";
import { getMyTaskList, saveUserTask } from "~/api/task";
export default {
  name: "courseDetail",
  components: {
    ChapterTree,
    VideosPlayer
  },
  data() {
    const validateIdNumber = (rule, value, callback) => {
      if (value === "") {
        callback(new Error("请输入身份证"));
      } else {
        if (
          !/^[1-9]\d{5}(18|19|([23]\d))\d{2}((0[1-9])|(10|11|12))(([0-2][1-9])|10|20|30|31)\d{3}[0-9Xx]$/.test(
            value
          )
        ) {
          callback(new Error("请输入正确的身份证"));
        }
        callback();
      }
    };
    return {
      // 课程评价
      comment_rank:'0',
      comment_list:[],
      comment:{
        total:0,
        page:1,
        pageSize:10
      },
      commentCount:{
        allRate:0,
        goodRate:0,
        mediumRate:0,
        badRate:0,
        goodPercentage:0,
      },

      myTaskList: [],
      taskObj: {},
      courseAgreementObj: null,
      agreementForm: {},
      agreementFormRule: {
        userName: [{ required: true, message: "请输入姓名", trigger: "blur" }],
        idNumber: [
          { validator: validateIdNumber, required: true, trigger: "blur" }
        ]
      },
      active_tap: "detail",
      course_obj: {
        name: ""
      },
      chapter_list: [], //章节列表
      chapter_tree: [], //章节树
      chapter_active: [], //折叠面板打开
      chapter_obj: {
        courseId: 0,
        chapterName: "",
        chapterIndex: 1,
        chapterLevel: 1,
        chapterDescription: "",
        fatherLevelId: 0,
        live: "hahah",
        courseWarePath: null,
        fileName: "",
        filePath: "",
        fileType: null,
        fileSize: null,
        createTime: 1591012869000,
        createUserId: null,
        createUserName: null,
        updateTime: 1591012869000,
        updateUserId: null,
        updateUserName: null
      }, //正在播放的章节
      component: "ChapterTree",
      component1: "ChapterWareTree",
      sources: "",
      is_had_course: false
    };
  },
  activated() {
    this.initPage();
  },
  filters:{
    formatRate(val){
      switch (val) {
        case 1:
          return "差评！课程太差了，我要吐槽！";
        case 2:
          return "勉强中评！课程不满意";
        case 3:
          return "中评！课程一般";
        case 4:
          return "好评！课程还不错，继续保持！";
        case 5:
          return "五星好评！课程非常棒，点赞！";
        default:
          return "";
      }
    }
  },
  computed: {
    ...mapState({
      user_info(state) {
        return state.user_info;
      },
      token(state) {
        return state.token;
      },
      major_list(state) {
        return state.major_list;
      },
      buy_record_list(state) {
        return state.buy_record_list;
      },
      kl_md(state) {
        return state.kl_md;
      },
      sign_Agreement_list(state) {
        return state.sign_Agreement_list;
      },
      is_mobile(state) {
        return state.is_mobile;
      },
      is_member(state) {
        return JSON.stringify(state.member_info) != "{}";
      },
      user_member(state) {
        return state.member_info;
      },
      member_discount(state) {
        return state.member_discount;
      }
    }),
    isShowCourseAgreement() {
      if (
        this.is_had_course &&
        this.courseAgreementObj &&
        Object.keys(this.courseAgreementObj).length > 0
      ) {
        let obj = this.sign_Agreement_list.findIndex(item => {
          return item.agreementId == this.courseAgreementObj.id;
        });
        if (obj != -1) {
          return false;
        } else {
          return true;
        }
      } else {
        return false;
      }
    },
    isMemberFree() {
      if (
        this.member_discount &&
        JSON.stringify(this.member_discount) !== "{}"
      ) {
        if (
          this.member_discount.majorIds.includes(this.course_obj.majorId) ||
          this.member_discount.courseIds.includes(this.course_obj.id)
        ) {
          return true;
        } else {
          return false;
        }
      }
    },
    courseId() {
      return this.$route.query.id;
    },
    chapterId() {
      return this.$route.query.chapterId;
    },
    isMircosoftRead() {
      const { courseWarePath } = this.chapter_obj;
      let xls = /^.*\.(?:xls)$/;
      let xlsx = /^.*\.(?:xlsx)$/;
      let docx = /^.*\.(?:docx)$/;
      let doc = /^.*\.(?:doc)$/;
      let ppt = /^.*\.(?:ppt)$/;
      let pptx = /^.*\.(?:pptx)$/;
      if (
        xls.test(courseWarePath) ||
        xlsx.test(courseWarePath) ||
        doc.test(courseWarePath) ||
        docx.test(courseWarePath) ||
        pptx.test(courseWarePath) ||
        ppt.test(courseWarePath)
      ) {
        return true;
      } else {
        return false;
      }
    },
    getCount() {
      let time_far =
        this.course_obj.buyCourseDeadlineDate - new Date().getTime();
      if (time_far > 0) {
        return time_far;
      } else {
        return -1;
      }
    },
    buyStatus(){
      let startTime = this.course_obj.buyCourseStartDate;
      let endTime = this.course_obj.buyCourseDeadlineDate;
      let nowTime = new Date().getTime();
      if(startTime > nowTime || endTime < nowTime){
        return true;
      }else{
        return false;
      }
    },
  },
  watch: {
    $route(new_val, old_val) {
      if (new_val.name == "coursedetail" && old_val.name == "coursedetail") {
        let chapter_obj = this.chapter_list.filter(
          i => i.id == new_val.query.chapterId
        )[0];
        console.log("chapter_obj", chapter_obj);
        this.$set(this, "chapter_obj", chapter_obj);
        if (this.chapter_obj && this.chapter_obj.isLive == 1) {
          this.sources = this.chapter_obj && this.chapter_obj.live;
        } else {
          this.sources = this.chapter_obj && this.chapter_obj.filePath;
        }
      }
    },
    courseId(new_val, old_val) {
      this.$nextTick(() => {
        this.initPage();
      });
    },
    buy_record_list(new_val, old_val) {
      this.set_had_course();
    }
  },
  methods: {
    ...mapActions(["initMember"]),
    ...mapMutations([
      "SET_IS_LOADING",
      "UPDATE_USERINFO",
      "UPDATE_BUYRECORD_LIST",
      "UPDATE_SIGN_AGREEMENT_LIST"
    ]),
    // 课程评价等级筛选
    commentHandle(v){
      console.log(v);
      this.comment.page = 1;
      this.getCourseComment();
    },
    // 课程评价分页
    commentChangePageHandle(page){
      window.scrollTo(0,this.$refs["left-position"].offsetTop);
      this.comment.page = page;
      this.getCourseComment();
    },
    // 获取课程评价
    async getCourseComment(){
      this.SET_IS_LOADING(true);
      let params = {
        courseId: this.courseId,
        offset: (this.comment.page - 1) * this.comment.pageSize,
        limit: this.comment.pageSize,
        sort: "id desc",
        rateType:this.comment_rank
      }
      let result = await getCourseCommentList(params);
      if (result && result.data && result.data.code == 200) {
        let data = result.data.data.rows.map(item => {
          return {
            ...item,
            acName: item.acName ? item.acName.substr(0, 1) + "****" : "无****"
          };
        });
        this.comment_list = data;
        this.comment.total = result.data.data.total;
      } else {
        
      }
      this.SET_IS_LOADING(false);
    },
    // 获取课程评价统计数据
    async getCommentCount(){
      this.SET_IS_LOADING(true);
      let params = {
        courseId: this.courseId,
      }
      let result = await getCommentCount(params);
      if (result && result.data && result.data.code == 200) {
        const { data } = result.data;
        this.commentCount = {
          ...data,
          goodPercentage : data.allRate == 0 ? 100 : data.goodPercentage
        }
        console.log(data);
      } else {
        
      }
      this.SET_IS_LOADING(false);
    },
    toLearn() {
      // 判断是否需要跳转 $router.push({ path: '/play', query: { id: courseId } })
      if (
        this.course_obj.isLive == 0 ||
        (this.course_obj.isLive == 2 && !this.course_obj.videoInfo)
      ) {
        this.$router.push({ path: "/play", query: { id: this.courseId } });
      }
    },
    async downloadExport(url, reportName) {
      this.SET_IS_LOADING(true);

      let result = await downloadReport(url);
      const content = result.data;
      const blob = new Blob([content]);
      let fileName = reportName + "." + url.replace(/(.*\.)/, ""); // 自定义文件名+后缀;
      if ("download" in document.createElement("a")) {
        console.log("非IE下载");
        // 非IE下载
        const elink = document.createElement("a");
        elink.download = fileName;
        elink.style.display = "none";
        elink.href = URL.createObjectURL(blob);
        document.body.appendChild(elink);
        elink.click();
        URL.revokeObjectURL(elink.href); // 释放URL 对象
        document.body.removeChild(elink);
      } else {
        // IE10+下载
        console.log("IE10+下载");
        navigator.msSaveBlob(content, fileName);
      }
      this.SET_IS_LOADING(false);
    },
    //上传我的作业
    async handleUploadTask(file) {
      console.log(file);
      this.SET_IS_LOADING(true);
      let params = {
        file: file,
        userId: this.user_info.id,
        taskId: this.taskObj.id
      };
      let fd = new FormData();
      Object.keys(params).forEach(i => {
        if (params[i] || params[i] === 0) {
          fd.append(i, params[i]);
        }
      });
      let result = await saveUserTask(fd);
      if (result && result.data && result.data.code == 200) {
        this.$Message.success("上传作业成功！");
        this.getChapterList();
        this.SET_IS_LOADING(false);
      } else if (result && result.data && result.data.code == 1001) {
        this.$Message.warning(result.data.msg);
        this.SET_IS_LOADING(false);
      } else {
        this.$Message.error("上传作业失败！");
        this.SET_IS_LOADING(false);
      }
      return false;
    },
    //设置我的作业报告的数据
    setTask(obj, status, event) {
      if (status) {
        this.$Message.warning("该作业您已经完成了哟");
        event.stopPropagation();
        return false;
      }
      if (obj && obj.taskType == 2) {
        this.taskObj = obj;
      } else {
        this.$router.push("/task-paper?taskId=" + obj.id);
      }
    },
    formatDate(time, type) {
      // console.log(time)

      var time = new Date(time);

      var y = time.getFullYear();
      var m = time.getMonth() + 1;
      var d = time.getDate();
      var h = time.getHours();
      var mm = time.getMinutes();
      var s = time.getSeconds();
      var add0 = m => {
        return m < 10 ? "0" + m : m;
      };
      if (type === 1) {
        return y + "-" + add0(m) + "-" + add0(d);
      } else if (type === 2) {
        return (
          y +
          "-" +
          add0(m) +
          "-" +
          add0(d) +
          " " +
          add0(h) +
          ":" +
          add0(mm) +
          ":" +
          add0(s)
        );
      } else if (type === 3) {
        return add0(h) + ":" + add0(mm) + ":" + add0(s);
      }
    },
    // 提交协议签署
    handleSubmitAgreement(name) {
      this.$refs[name].validate(async valid => {
        if (valid) {
          let params = {
            ...this.agreementForm,
            userId: this.user_info.id,
            agreementId: this.courseAgreementObj.id
          };
          let result = await saveCourseAgreement(params);
          if (result && result.data && result.data.code == 200) {
            this.UPDATE_SIGN_AGREEMENT_LIST(result.data.data);
          } else {
            this.$Message.error("签署失败");
          }
        } else {
          // this.$Message.error('Fail!');
        }
      });
    },
    async getCourseAgreement() {
      this.SET_IS_LOADING(true);
      let result = await getCourseAgreement(this.courseId);
      if (result && result.data && result.data.code == 200) {
        this.courseAgreementObj = result.data.data;
      } else {
        this.$Message.error("获取失败");
      }
      this.SET_IS_LOADING(false);
    },
    async getData() {
      this.SET_IS_LOADING(true);
      let result = await getCourseDetailById({
        courseId: this.courseId
      });
      if (result && result.data && result.data.code == 200) {
        // 加一层折扣时间的判断,不在折扣时间内判定为不是折扣课程
        let { data } = result.data;
        let currentTime = new Date().getTime();
        if(!(data.isDiscount == 1 && currentTime >= data.discountStartTime && data.discountEndTime >= currentTime)){
          this.course_obj = {
            ...data,
            isDiscount:0
          }
        }else{
          this.course_obj = data;
        }
        // this.course_obj = result.data.data;
      } else {
        this.$Message.error("获取失败");
      }
      this.SET_IS_LOADING(false);
    },
    set_had_course() {
      let res = this.buy_record_list.filter(i => i.courseId == this.courseId);
      console.log(res, "===============更新===================");
      if (res.length > 0 && res[0].deleted === 0) {
        this.is_had_course = true;
      } else {
        this.is_had_course = false;
      }
    },
    arrToTree(trimChapterList) {
      let _LEVEL_OBJECT = {};
      //找出最深的层数
      let _MAX_ = trimChapterList.reduce((accumulator, currentValue) => {
        if (accumulator.chapterLevel > currentValue.chapterLevel) {
          return accumulator;
        } else {
          return currentValue;
        }
      }).chapterLevel;
      if (!_MAX_) {
        return trimChapterList;
      }
      console.log("_MAX_:", _MAX_);
      for (let i = 1; i < _MAX_ + 1; i++) {
        _LEVEL_OBJECT = {
          ..._LEVEL_OBJECT,
          [i]: trimChapterList
            .map((item, index) => {
              if (item.chapterLevel == i) {
                return item;
              }
            })
            .filter(item => item !== undefined)
        };
      }
      for (let i = _MAX_; i >= 1; i--) {
        if (i < _MAX_) {
          _LEVEL_OBJECT[i] = _LEVEL_OBJECT[i].map((item, index) => {
            return {
              ...item,
              children: _LEVEL_OBJECT[i + 1]
                .map((item2, index2) => {
                  if (item2.fatherLevelId == item.id) {
                    return item2;
                  }
                })
                .filter(item2 => item2 !== undefined)
            };
          });
        }
      }
      console.log("_LEVEL_OBJECT:", _LEVEL_OBJECT);
      return _LEVEL_OBJECT[1];
    },
    async getChapterList() {
      return new Promise(async (res, rej) => {
        this.SET_IS_LOADING(true);
        let result = await getChapter({
          courseId: this.courseId
        });
        if (result && result.data && result.data.code == 200) {
          const { data } = result.data;
          if (data && data.rows && data.rows.length > 0) {
            this.chapter_list = data.rows;
            if (this.token && Object.keys(this.user_info).length > 0) {
              await this.getMyTask();
            }
            console.log(this.myTaskList);
            if (this.myTaskList.length > 0) {
              this.myTaskList.forEach(v => {
                this.chapter_list = data.rows.map(item => {
                  if (item.id == v.videoId) {
                    return {
                      ...item,
                      taskId: v.id,
                      taskType: v.taskType,
                      userTask: v.userTask ? v.userTask : null
                    };
                  } else {
                    return {
                      ...item
                    };
                  }
                });
              });
            }
            // 解析章节名称
            this.myTaskList = this.myTaskList.map(item => {
              let obj = data.rows.find(videoItem => {
                return item.videoId == videoItem.id;
              });
              if (obj) {
                return {
                  ...item,
                  videoName: obj.chapterName
                };
              } else {
                return {
                  ...item,
                  videoName: "未知"
                };
              }
            });
            let trimChapterList = this.chapter_list.map(i => {
              return {
                ...i,
                children: [],
                title: i.chapterName,
                expand: true
              };
            });
            // this.chapter_tree = this.arrToTree(trimChapterList);
            // console.log('trimChapterList',trimChapterList);
            this.chapter_tree = this.orderList(
              this.handleTree(trimChapterList, "id", "fatherLevelId")
            );
            this.chapter_active = this.chapter_list.map(i => i.id);
            let chapter_arr = this.chapter_list.filter(
              i => i.id == this.chapterId
            );
          }
        } else {
          this.$Message.error(
            "获取失败！",
            result && result.data && result.data.msg
          );
        }
        this.SET_IS_LOADING(false);
        res();
      }).then();
    },
    /**
     * 构造树型结构数据
     * @param {*} data 数据源
     * @param {*} id id字段 默认 'id'
     * @param {*} parentId 父节点字段 默认 'parentId'
     * @param {*} children 孩子节点字段 默认 'children'
     */
    handleTree(data, id, parentId, children) {
      let config = {
        id: id || "id",
        parentId: parentId || "parentId",
        childrenList: children || "children"
      };

      var childrenListMap = {};
      var nodeIds = {};
      var tree = [];
      for (let d of data) {
        let parentId = d[config.parentId];
        if (childrenListMap[parentId] == null) {
          childrenListMap[parentId] = [];
        }
        nodeIds[d[config.id]] = d;
        childrenListMap[parentId].push(d);
      }
      for (let d of data) {
        let parentId = d[config.parentId];
        if (nodeIds[parentId] == null) {
          tree.push(d);
        }
      }
      for (let t of tree) {
        adaptToChildrenList(t);
      }
      function adaptToChildrenList(o) {
        if (childrenListMap[o[config.id]] !== null) {
          o[config.childrenList] = childrenListMap[o[config.id]]
            ? childrenListMap[o[config.id]]
            : [];
        }
        if (o[config.childrenList]) {
          for (let c of o[config.childrenList]) {
            adaptToChildrenList(c);
          }
        }
      }
      return tree;
    },
    // 排序
    orderList(data) {
      data.map(item => {
        if (item.children && item.children.length > 0) {
          return this.orderList(item.children);
        } else {
          return item;
        }
      });
      return data.sort((a, b) => {
        return b.orderNumber - a.orderNumber;
      });
    },
    trimDate(date) {
      if (date) {
        let _date = new Date(date);
        return `${_date.getFullYear()}-${_date.getMonth() +
          1}-${_date.getDate()}`;
      } else {
        return this.$t("locale.pc.mycourse.coursedetail.unknow");
      }
    },
    //blob转base64在调用downloadjs下载
    async handleDownload(url) {
      if (process.client) {
        const { download } = require("~/static/js/download2.js");
        let result = await downloadFile(url);
        // console.log("result:", result);
        if (result && result.status == 200) {
          let mime_type = getMimeType(url);
          download(
            result.data,
            this.chapter_obj &&
              this.chapter_obj.chapterName + "." + mime_type.str,
            mime_type.mime
          );
        }
      }
    },
    //获取我的作业
    async getMyTask() {
      this.SET_IS_LOADING(true);
      let params = {
        courseId: this.courseId
      };
      let result = await getMyTaskList(params);
      if (result && result.data && result.data.code == 200) {
        this.myTaskList = result.data.data.rows.map(item => {
          return {
            ...item,
            videoHierarchy: item.videoHierarchy
              ? JSON.parse(item.videoHierarchy)
              : []
          };
        });
      } else {
        this.$Message.error(this.$t("locale.pc.classroom.t43"));
      }
      this.SET_IS_LOADING(false);
    },
    initPage() {
      this.getData();
      this.getChapterList();
      this.set_had_course();
      this.initMember();
      this.getCommentCount();
      this.getCourseComment();
      if (this.token && Object.keys(this.user_info).length > 0) {
        this.getCourseAgreement();
      }
    },
    turnString(num) {
      var re = /^[0-9]+$/;
      var re2 = /^[0-9]+(\.[0-9]{1})$/;
      if (re.test(num)) {
        num += ".00";
      }
      if (re2.test(num)) {
        num += "0";
      }
      return num;
    },
    async handleApply() {
      if (!this.token && Object.keys(this.user_info).length == 0) {
        this.$router.replace("/login");
        return;
      }
      let __price__ = this.course_obj.isFree
        ? 0
        : this.course_obj.isDiscount
        ? this.course_obj.discountPrice
        : this.course_obj.price;
      this.SET_IS_LOADING(true);
      let params = {
        courseId: this.courseId,
        userId: this.user_info.id,
        price: this.turnString(__price__)
      };
      let result = await saveOrder(params);
      if (result && result.data && result.data.code == 200) {
        const { balance, id, courseId, userId } = result.data.data;
        let update_obj = {
          balance
        };
        let course_update_obj = {
          id,
          courseId,
          userId
        };
        this.UPDATE_USERINFO(update_obj);
        this.UPDATE_BUYRECORD_LIST(course_update_obj);
        this.SET_IS_LOADING(false);
        this.$Message.success(this.$t("locale.pc.mycourse.coursedetail.t27"));
      } else {
        this.SET_IS_LOADING(false);
        this.$Message.success(
          this.$t("locale.pc.mycourse.coursedetail.t28") + result &&
            result.data &&
            result.data.data
        );
      }
    }
  },
  created() {
    this.initPage();
  },
  mounted() {}
};
</script>
<style lang="scss">
.page-coursedetail {
  @import "assets/css/richtext.scss";
  display: flex;
  background-color: #f2f2f2;
  width: 100%;
  height: 100%;
  padding-bottom: 20px;
  .section_comment{
    .comment_filter{
      background: #f4f4f4;
      border: 1px solid #e5e5e5;
      padding: 10px 0;
      position: relative;
      .comment_statistics{
        display: inline-block;
        vertical-align: middle;
        text-align: center;
        width: 125px;
        border-right: 1px solid #e5e5e5;
        margin: -5px 0;
        font-size: 16px;
        .statistics_num{
          color: #e85308;
          font-size: 28px;
          line-height: 1;
          display: block;
        }
      }
      .filter_comment_rank{
        display: inline-block;
        margin-left: 15px;
      }
    }
    .comment_list{
      .comment_item{
        position: relative;
        padding: 20px 10px 20px 0px;
        border-top: 1px solid #e5e5e5;
        display: flex;
        &:first-child{
          border-top:none;
        }
        .item_left{
          width: 80px;
          text-align: center;
          .user_avatar{
            width: 40px;
            height: 40px;
            display: block;
            border-radius: 50%;
            background: red;
            overflow: hidden;
            margin: 0 auto;
          }
          .user_name{
            font-size: 14px;
            line-height: 1.5;
            color: #333;
            overflow: hidden;
            text-overflow: ellipsis;
            white-space: nowrap;
            padding: 0 6px;
          }
        }
        .item_right{
          width: 720px;
          .star_list{
            display: flex;
            justify-content: space-between;
          }
          .comment_bd{
            font-size: 14px;
            line-height: 1.5;
            color: #333;
            word-wrap: break-word;
            margin-bottom: 10px;
          }
          .comment_ft{
            color: #999;
            .comment_time{
              font-size: 14px;
              line-height: 1.5;
            }
          }
          .comment_reply{
            padding: 20px 0;
            position: relative;
            border-top: 1px dashed #e5e5e5;
            margin-top: 20px;
            margin-bottom: -20px;
            font-size: 14px;
            line-height: 1.5;
            .reply_bd{
              color: #ae8651;
              margin-bottom: 10px;
              .reply_tt{
                font-weight: 400;
                word-wrap: break-word;
              }
            }
          }
        }
      }
    }
  }
  .course_task_list {
    // padding: 48px 0;
    padding: 10px 0;
    .task_item {
      padding: 0 20px;
      // padding: 0 60px;
      box-sizing: border-box;
      display: flex;
      align-items: center;
      justify-content: space-between;
      margin-bottom: 10px;
      .task_name {
        font-size: 16px;
        letter-spacing: 2px;
        // white-space: nowrap;
        // overflow: hidden;
        // text-overflow: ellipsis;
        font-style: italic;
      }
      .task_btn_list {
        // width: 336px;
        width: 230px;
        display: flex;
        .task_btn_item {
          width: 88px;
          height: 36px;
          font-size: 14px;
          border-radius: 6px;
          border: solid 1px var(--theme-color);
          text-align: center;
          line-height: 36px;
          color: var(--theme-color);
          margin-left: 24px;
          cursor: pointer;
          &.task_btn_gray {
            border: solid 1px #b3b3b3;
            color: #b3b3b3;
          }
          &.task_btn_pink {
            border: solid 1px #ff8a8a;
            color: #ff8a8a;
          }
        }
      }
    }
  }
  .empty_task {
    font-size: 16px;
    text-align: center;
    padding: 20px 0;
    p {
      margin-top: 10px;
    }
  }
  .line {
    width: 100%;
    height: 1px;
    background-color: #f2f2f2;
  }
  .page-position {
    width: 1200px;
    margin: 0 auto;
    .breadcrumb-box {
      height: 20px;
      display: flex;
      align-items: center;
      padding: 30px 0;
      .breadcrumb-item {
        color: #515a6e;
        font-size: 14px;
        text-align: left;
        font-family: SourceHanSansSC-regular;
        &:hover {
          color: #515a6e;
        }
      }
      .breadcrumb-arrow {
        display: flex;
        align-items: center;
        margin: 0 3px;
        color: #515a6e;
      }
    }
    .top-introduce {
      font-family: Roboto;
      border: 1px solid rgba(255, 255, 255, 0);
      width: 1200px;
      height: 400px;
      background-color: #ffffff;
      border-radius: 4px;
      overflow: hidden;
      display: flex;
      // align-items: center;
      box-sizing: border-box;
      padding: 50px 60px;
      .img-position {
        width: 450px;
        height: 300px;
        position: relative;
        > img {
          width: 100%;
          height: 100%;
          display: block;
        }
        .box-play {
          position: absolute;
          width: 100%;
          height: 100%;
          left: 0;
          top: 0;
          right: 0;
          bottom: 0;
          background-color: #1f2329;
          border-radius: 2px;
          opacity: 0.5;
        }
        .play {
          position: absolute;
          margin: auto;
          left: 0;
          top: 0;
          right: 0;
          bottom: 0;
          width: 85px;
          height: 85px;
          border: solid 3px #edf0f5;
          border-radius: 50%;

          opacity: 1;
        }
      }
      .center-content {
        box-sizing: border-box;
        padding-left: 36px;
        // width: 750px;
        width: 628px;
        // background: chartreuse;
        .title {
          font-size: 18px;
          font-weight: bold;
          line-height: 30px;
          color: #43474c;
          display: -webkit-box;
          -webkit-line-clamp: 2;
          overflow: hidden;
          text-overflow: ellipsis;
          -webkit-box-orient: vertical;
          height: 60px;
        }
        .chapter-people {
          display: flex;
          justify-content: space-between;
          margin: 12px 0;
          .chapter-number {
            font-size: 16px;
            font-weight: bold;
            line-height: 30px;
            .number {
              font-size: 28px;
              font-weight: bold;
              color: var(--theme-color);
            }
            .people {
              font-size: 18px;
              font-weight: bold;
              color: #ff8a8a;
            }
          }
          .buy-people {
            font-size: 16px;
            font-weight: bold;
            line-height: 30px;
            // color: #8b9199;
            .people {
              font-size: 18px;
              font-weight: bold;
              color: #ff8a8a;
            }
          }
        }
        .course-date {
          font-size: 14px;
          font-weight: bold;
          line-height: 16px;
          margin-bottom: 10px;
        }
        .course-info {
          font-size: 14px;
          font-weight: bold;
          color: #5a5f66;
          line-height: 20px;
          margin-bottom: 16px;
          .info {
            text-indent: 2em;
            display: -webkit-box;
            -webkit-line-clamp: 3;
            overflow: hidden;
            text-overflow: ellipsis;
            -webkit-box-orient: vertical;
            height: 60px;
          }
        }
        .online {
          width: 100%;
          height: 1px;
          background-color: #e9ebf0;
        }
        .buy-price {
          margin-top: 20px;
          // display: flex;
          // justify-content: space-between;
          overflow: hidden;
          .member-price {
            float: left;
            width: 209px;
            height: 36px;
            background-image: url("/img/pc/member-price-bg.png");
            background-repeat: no-repeat;
            background-size: 100% 100%;
            // padding: 0 40px 0 20px;
            text-align: center;
            line-height: 36px;

            color: #ffffff;
            .m-f {
              font-size: 22px;
            }
            .m-t {
              font-size: 14px;
            }
            .m-p {
              font-size: 24px;
            }
          }
          .original-price {
            float: right;
            display: flex;
            align-items: center;
          }
        }
      }
    }
    .main-box {
      display: flex;
      .video-container {
        width: 850px;
        height: 473px;
      }
      .chapter-box {
        flex: 1;
        background-color: #fff;
        margin-left: 20px;
        padding: 0 12px 0 0;
        border-radius: 4px;
        height: 536px;
        overflow: auto;
        &::-webkit-scrollbar {
          height: 10px;
          width: 3px;
          border-radius: 3px;
          background-color: #fff;
        }
        &::-webkit-scrollbar-button {
          height: 0;
          width: 0;
          display: none;
        }
        &::-webkit-scrollbar-thumb {
          // background-color: hsla(0, 0%, 95.7%, 1);
          background-color: var(--theme-color);
          opacity: 0.6;
        }
      }
    }
    .body-position {
      width: 100%;
      // height: 100%;
      margin-top: 20px;
      .left-detail {
        display: block;
        float: left;
        padding: 20px 20px;
        width: 850px;
        min-height: 500px;
        // height: 100%;
        border-radius: 4px;
        background-color: #ffffff;
        .Angle {
          margin: 33px 0px 33px 35px;
          > img {
            float: left;
            margin-top: 4px;
          }
          > p {
            margin-left: 35px;
            width: 100%;
            line-height: 29px;
            font-weight: 600;
            color: rgba(16, 16, 16, 1);
            font-size: 20px;
            text-align: left;
            font-family: SourceHanSansSC-bold;
          }
        }
        > p {
          width: 701px;
          height: 376px;
          margin: 0px 49px 0px 100px;
          font-family: SourceHanSansSC;
          font-weight: 400;
          font-size: 16px;
          color: rgb(16, 16, 16);
          font-style: normal;
          letter-spacing: 0px;
          line-height: 24px;
          text-decoration: none;
        }
        .introduce {
          @import "assets/css/richtext.scss";
          h3 {
            font-size: 18px;
            color: #010101;
            margin: 5px 0;
          }
          .id-it {
            margin: 22px 0;
            font-size: 14px;
          }
		  .ql-editor {
		    white-space: unset;
		  }
          // .rich-text {
          // }
        }
        .chapter-info {
          .chapter-modules {
            display: flex;
            align-items: center;
            flex-wrap: wrap;
            font-size: 16px;
            color: #333;
            font-weight: 700;
            &::before {
              content: "";
              margin-right: 5px;
              display: block;
              background-color: var(--theme-color);
              width: 7px;
              height: 22px;
              border-radius: 2px;
            }
          }
          .chapter-box {
            padding: 16px;
          }
        }
      }
      .right-mentor {
        float: right;
        width: 330px;
        min-height: 500px;
        border-radius: 4px;
        background-color: #ffffff;
        > span {
          display: block;
          margin: 21px 0px 6px 19px;
          font-family: SourceHanSansSC;
          font-weight: 700;
          font-size: 20px;
          color: rgb(16, 16, 16);
          font-style: normal;
          letter-spacing: 1px;
          line-height: 29px;
          text-decoration: none;
        }
        .online {
          width: 100%;
          height: 1px;
          background-color: #e9ebf0;
        }
        .mentor-mess {
          margin: 26px 21px;
          height: 70px;
          .portrait {
            border: 1px solid rgb(187, 187, 187);
            border-radius: 50px;
            width: 72px;
            height: 72px;
            float: left;
            > img {
              width: 100%;
              height: 100%;
              border-radius: 50px;
              overflow: hidden;
            }
          }
          .abstract {
            width: 195px;
            height: 70px;
            float: right;
            .m1 {
              font-family: SourceHanSansSC;
              font-weight: 400;
              font-size: 14px;
              color: rgb(16, 16, 16);
              font-style: normal;
              letter-spacing: 0px;
              line-height: 20px;
              text-decoration: none;
              margin-top: 2px;
              > p {
                float: left;
                font-weight: 700;
                font-size: 18px;
                color: var(--theme-color);
                letter-spacing: 0px;
                margin-right: 10px;
              }
            }
            .m2 {
              font-family: SourceHanSansSC;
              font-weight: 400;
              font-size: 12px;
              color: rgb(16, 16, 16);
              font-style: normal;
              letter-spacing: 0px;
              line-height: 20px;
              text-decoration: none;
              margin: 6px auto;
            }
            .m3 {
              font-family: SourceHanSansSC;
              font-weight: 400;
              font-size: 12px;
              color: rgb(16, 16, 16);
              font-style: normal;
              letter-spacing: 0px;
              line-height: 20px;
              text-decoration: none;
              > p {
                float: left;
              }
            }
          }
        }
        .teacher_introduce {
          margin: 10px 21px;
          font-size: 14px;
        }
      }
    }
  }
  .course-agreement {
    z-index: 1005;
    overflow: hidden;
    position: fixed;
    top: 0;
    left: 0;
    right: 0;
    bottom: 0;
    background-color: rgba(0, 0, 0, 0.3);
    .agreement-box {
      position: relative;
      top: 90px;
      width: 800px;
      margin: 0 auto;
      background-color: #fff;
      z-index: 1005;
      outline: 0;
      border-radius: 3px;
      overflow: hidden;
      .agreement-header {
        width: 100%;
        height: 50px;
        text-align: center;
        line-height: 50px;
        font-size: 16px;
        border-bottom: 1px solid #ddd;
      }
      .agreement-content {
        width: 100%;
        min-height: 60vh;
        max-height: 60vh;
        overflow: auto;
        padding: 10px;
        box-sizing: border-box;
      }
      .agreement-footer {
        width: 100%;
        height: 64px;
        border-top: 1px solid #ddd;
        vertical-align: middle;
        .footer-form {
          margin-top: 6px;
          margin-left: 10px;
        }
      }
    }
  }
}
</style>
